<?php
class LinkModel extends Model{
	private $table;

	public function __construct(){
		parent::__construct();

		$this->table = C('db_table_prefix').'links';
	}
	
	/**
	 * 获取指定分类的网址列表
	 * @param int $cid
	 * @return array $links
	 */
	public function getLinksByCid($cid){
		if(empty($cid)){
			return array();
		}
		$categories = array();
		$sql = "SELECT `id`,`cid`,`name`,`url`,`description` 
				FROM `{$this->table}` 
				WHERE `status`=1 AND `cid`='{$cid}' 
				ORDER BY `id` ASC";
		$links = $this->query($sql);

		return $links;
	}

	/**
	 * 获取单条或全部网址列表
	 * @param int $id
	 * @return array $links
	 */
	public function linkList($id=null){
		$categories = array();
		$sql = "SELECT `id`,`cid`,`name`,`url`,`description` FROM `{$this->table}` WHERE `status`=1";
		if($id){
			$sql .= " AND `id`='{$id}'";
		}
		$sql .= " ORDER BY `id` ASC";
		$links = $this->query($sql);

		return $links;
	}

	/**
	 * 获取单条网址数据
	 */
	public function getLinkById($id){
		if(empty($id)){
			return false;
		}
		$link = $this->linkList($id);
		
		return $link[0];
	}
	
	/**
	 * 获取所有网址数据
	 */
	public function getLinks(){
		$linksTable = C('db_table_prefix').'links';
		$categoriesTable = C('db_table_prefix').'categories';
		$sql = "SELECT A.*,B.name AS `cat_name`,B.`order` 
				FROM `{$linksTable}` A LEFT JOIN `{$categoriesTable}` B ON A.`cid`=B.id 
				WHERE A.`status`='1' AND B.`status`='1'
				ORDER BY B.`order` ASC,B.`id` ASC;";
		$result = $this->query($sql);
		if( ! empty($result)){
			foreach($result as $val){
				$links[$val['cid']][] = $val;
			}
		}
		
		return $links;
	}

	/**
	 * 添加网址
	 */
	public function addLink($data){
		$time = time();
		$sql = "INSERT INTO `{$this->table}`
			(`cid`,`name`,`url`,`description`,`ctime`,`utime`)
			VALUES ('{$data['cid']}','{$data['name']}','{$data['url']}','{$data['description']}','{$time}','{$time}')";
		$result = $this->execute($sql);

		return $result;
	}
	
	/**
	 * 编辑网址
	 * @param array $data array('id'=>'','name'=>'','desc'=>'')
	 * @return boolean true or false
	 */
	public function editLink($data){
		if(empty($data['id'])){
			return false;
		}
		$utime = time();
		$sql = "UPDATE `{$this->table}` SET `cid`='{$data['cid']}',`name`='{$data['name']}',`url`='{$data['url']}',`description`='{$data['description']}',`utime`='{$utime}' WHERE `id`='{$data['id']}' LIMIT 1";
		$result = $this->execute($sql);

		return $result;
	}
	
	/**
	 * 删除网址
	 * @param int $id
	 * @return boolean true or false
	 */
	public function delLink($id){
		if(empty($id)){
			return false;
		}
		$sql = "UPDATE `{$this->table}` SET `status`='0' WHERE `id`='{$id}' LIMIT 1";
		$result = $this->execute($sql);
		
		return $result;
	}
	
}